//
//  MBCommodityDetailTipsModel.swift
//  StarTimesON
//
//  Created by Toj on 8/22/22.
//  Copyright © 2022 StarTimes. All rights reserved.
//

import UIKit

class MBCommodityDetailTipsModel: NSObject {
    
    private(set) var commodity: MemberCommodityDto?
    private(set) var bottomMargin: CGFloat = 0
    
    var introduceHeight = CGFloat.zero
    var tipsSize = CGSize.zero
    var introduceAttributed: NSAttributedString?
    var user_notification = ""
    
    func setTipsModel(commodity: MemberCommodityDto?) {
        self.commodity = commodity
        
        let width = KScreenW - 32.ui_scale // 16 * 2
        guard let model = commodity else {
            tipsSize = .zero
            introduceAttributed = nil
            user_notification = ""
            return
        }
        // 价格计划 高度
        var planHeight = CGFloat.zero
        user_notification = model.matched_commodity_plan?.user_notification ?? ""
        if !user_notification.isEmpty  {
            planHeight = user_notification.st_stringHeight(font: UIFont.systemFont(ofSize: 12.f_scale), maxWidth: width - 16.ui_scale) // 8 *2
            planHeight = planHeight + 16.ui_scale // 上下间距
        }
        
        let language = LanguageManager.currentLanguage()
        var htmlText = model.commodity_specifications_en ?? ""
        switch language {
        case "fr":
            htmlText = model.commodity_specifications_fr ?? ""
        case "pt":
            htmlText = model.commodity_specifications_pt ?? ""
        case "sw":
            htmlText = model.commodity_specifications_sw ?? ""
        default:
            break
        }
        htmlText.st_removeLast(string:"<span><br></span>")
        var specHeight = CGFloat.zero
        let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [.documentType:NSAttributedString.DocumentType.html]
        if htmlText.count > 0,
           let data = htmlText.data(using: .unicode, allowLossyConversion: true),
           let attrStr = try? NSMutableAttributedString(data: data, options: options, documentAttributes: nil) {
            let attrs: [NSAttributedString.Key: Any] = [
                .font: UIFont.systemFont(ofSize: 12.f_scale),
                .foregroundColor: "#999999".to_color
            ]
            let range = NSRange(location: 0, length: attrStr.length)
            attrStr.addAttributes(attrs, range: range)
            specHeight = attrStr.st_stringHeight(maxWidth: width)
            bottomMargin = htmlText.contains("<ul") ? 0 : 12
            // print("-->toj: htmlText: \(htmlText)")
            // print("-->toj: specHeight: \(specHeight)")
            introduceAttributed = attrStr
        }
        
        var cellHeight = planHeight + specHeight + 0.1
        if planHeight > 0 && specHeight > 0 {
            cellHeight += 8
        }
        introduceHeight = specHeight
        tipsSize = CGSize(width: width, height: cellHeight)
    }
}
